package com.ruipeng.shengyapo.controller;

import com.ruipeng.shengyapo.dao.OrderMapper;
import com.ruipeng.shengyapo.service.OrderService;
import com.ruipeng.shengyapo.service.UserService;
import com.ruipeng.shengyapo.utils.ObjUtils;
import com.ruipeng.shengyapo.utils.XmlUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by tu_pei on 17/5/28. 支付相关
 */

@Controller
public class WXPayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    /**
     * 微信异步回调，不会跳转页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/notifyUrl")
    public String weixinReceive(HttpServletRequest request, HttpServletResponse response, Model model)throws Exception{
        System.out.println("==开始进入h5支付回调方法==");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        InputStream in=request.getInputStream();
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buffer =new byte[1024];
        int len=0;
        while((len=in.read(buffer))!=-1){
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
        String msgxml=new String(out.toByteArray(),"utf-8");//xml数据
        System.out.println(msgxml);
        Map map =  XmlUtil.xml2map(msgxml,false);
        String result_code=(String) map.get("result_code");
        String out_trade_no  = (String) map.get("out_trade_no");

        System.out.println("out_trade_no="+out_trade_no);

        String total_fee  = (String) map.get("total_fee");
        String userId  = (String) map.get("attach");
        //Double amount=new Double(total_fee);//获取订单金额

        if(result_code.equals("SUCCESS") ){
            //总金额以分为单位，不带小数点
            double order_total_fee = Double.parseDouble(total_fee);
            System.out.println("userId="+userId);
            Integer trade_type  = Integer.parseInt(userId.substring(userId.indexOf(",")+1,userId.length()));
            System.out.println("trade_type="+trade_type);
            // 官方签名工具地址：https://pay.weixin.qq.com/wiki/tools/signverify/
            System.out.println("微信签名成功.... TNND");
            //更新订单状态
            Map<String,Object> orderMap = new HashMap<>();
            orderMap.put("rechgId",ObjUtils.getNowDate() + ObjUtils.randomNumeric(4)+"00100"+ObjUtils.randomNumeric(6)+"00"+ObjUtils.randomNumeric(4));
            orderMap.put("rechargeType",trade_type);
            userId = userId.toString().substring(0,userId.indexOf(","));
            orderMap.put("userId",userId);
            orderMap.put("rechargeWay",0);
            orderMap.put("rechgrgeAmount",order_total_fee/100);
            orderMap.put("tradeInfo",map.toString());
            orderMap.put("tradeStatus",1);
            orderMap.put("otherNo",(String) map.get("out_trade_no"));

            System.out.println();

            orderService.addOrderInfo(orderMap);

            Map<String,Object> updateUser = new HashMap<String,Object>();
            updateUser.put("userId",userId);
            System.out.println("trade_type="+order_total_fee);
            if(trade_type == 1){
                System.out.println("充值="+order_total_fee);
                //充值
                updateUser.put("userAccount",order_total_fee/100);
            }
            if(trade_type == 2){
                System.out.println("交押金="+order_total_fee);
                //交押金
                updateUser.put("deposit",order_total_fee/100);
            }
            if(trade_type == 3){
                //退押金
                System.out.println("退押金="+order_total_fee/100);
                updateUser.put("deposit",0);
            }
            //更新用户余额或者押金
            System.out.println("  =updateUser="+JSONObject.fromObject(updateUser));
            userService.updateUserInfo(updateUser);


            response.getWriter().write(setXml("SUCCESS", "OK"));    //告诉微信已经收到通知了
        }else{
            System.out.println("微信签名失败");
            response.getWriter().write(setXml("SUCCESS", "OK"));    //告诉微信已经收到通知了
        }

        return null;
    }
    public static String setXml(String return_code,String return_msg){
        return "<xml><return_code><![CDATA["+return_code+"]]></return_code><return_msg><![CDATA["+return_msg+"]]></return_msg></xml>";
    }
}
